{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# p08: Eigenvalues of harmonic oscillator $-u'' + x^2 u$ on $R$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "%config InlineBackend.figure_format='svg'\n",
    "from numpy import pi,arange,linspace,sin,zeros,diag,sort\n",
    "from scipy.linalg import toeplitz\n",
    "from numpy.linalg import eig"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "N = 6\n",
      "   4.614729169954779e-01\n",
      "   7.494134621050524e+00\n",
      "   7.720916053006571e+00\n",
      "   2.883248377834012e+01\n",
      "N = 12\n",
      "   9.781372812985968e-01\n",
      "   3.171605320647182e+00\n",
      "   4.455935291166784e+00\n",
      "   8.924529058119930e+00\n",
      "N = 18\n",
      "   9.999700014993145e-01\n",
      "   3.000644066795838e+00\n",
      "   4.992595324407719e+00\n",
      "   7.039571897981494e+00\n",
      "N = 24\n",
      "   9.999999976290300e-01\n",
      "   3.000000098410869e+00\n",
      "   4.999997965273287e+00\n",
      "   7.000024998156534e+00\n",
      "N = 30\n",
      "   9.999999999999725e-01\n",
      "   3.000000000000748e+00\n",
      "   4.999999999975604e+00\n",
      "   7.000000000508605e+00\n",
      "N = 36\n",
      "   9.999999999999993e-01\n",
      "   3.000000000000012e+00\n",
      "   5.000000000000010e+00\n",
      "   7.000000000000001e+00\n"
     ]
    }
   ],
   "source": [
    "L = 8.0\n",
    "for N in range(6,37,6):\n",
    "    h = 2.0*pi/N; x = h*linspace(1,N,N); x = L*(x-pi)/pi\n",
    "    col = zeros(N)\n",
    "    col[0] = -pi**2/(3.0*h**2) - 1.0/6.0\n",
    "    col[1:] = -0.5*(-1.0)**arange(1,N)/sin(0.5*h*arange(1,N))**2\n",
    "    D2 = (pi/L)**2 * toeplitz(col)\n",
    "    evals,evecs = eig(-D2 + diag(x**2))\n",
    "    eigenvalues = sort(evals)\n",
    "    print \"N = %d\" % N\n",
    "    for e in eigenvalues[0:4]:\n",
    "        print \"%24.15e\" % e"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python [default]",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
